import type { UserRoleConfigurationModalPropsType } from './typings'
import { ref } from 'vue'
import { useStore } from 'vuex'
import { ElDialog, ElTree, ElButton, ElMessage } from 'element-plus'
import useVuexGetters from '~/hooks/useVuexGetters'

export default function UserRoleConfigurationModal(props: UserRoleConfigurationModalPropsType) {
  const { visible, cancel } = props
  const store = useStore()
  const loadingRef = ref<boolean>()
  const roleIdsRef = ref<string[]>([])
  const systemRoleState = useVuexGetters('systemRole', ['userRoleSelectList', 'userRoleEnum'])

  // 提交
  const handleSubmit = async () => {
    if (!roleIdsRef?.value?.length) {
      ElMessage({ type: 'warning', message: '请选择至少一条数据' })
      return
    }
    loadingRef.value = true
    const res = await store.dispatch('systemUser/UpdateSystemUserRoleGrant', {
      userIds: props.users?.map((item) => item.id)?.join(','),
      roleIds: roleIdsRef?.value?.join(',')
    })
    loadingRef.value = false
    if (res?.code === 200) {
      ElMessage({ type: 'success', message: '操作成功' })
      cancel()
    }
  }

  return (
    <ElDialog
      title="用户角色配置"
      modelValue={visible}
      closeOnClickModal={false} // 点遮罩层不关弹窗
      draggable // 可拖拽
      beforeClose={cancel}
      v-slots={{
        footer: () => (
          <>
            <ElButton type="primary" loading={loadingRef.value} onClick={handleSubmit}>
              保存
            </ElButton>
            <ElButton onClick={cancel}>取消</ElButton>
          </>
        )
      }}
    >
      <ElTree
        data={systemRoleState.userRoleSelectList.value}
        show-checkbox
        nodeKey="id"
        defaultExpandAll
        props={{
          label: 'title'
        }}
        defaultCheckedKeys={
          props.users?.length === 1 ? (props.users[0]?.roleId as string)?.split?.(',') || [] : []
        }
        onCheck={(_, { checkedKeys }) => {
          roleIdsRef.value = checkedKeys
        }}
      />
    </ElDialog>
  )
}
